package com.steam.xbcc.security;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.steam.xbcc.domain.Login;
import com.steam.xbcc.domain.Permission;
import com.steam.xbcc.dto.LoginContextDto;
import com.steam.xbcc.service.ILoginService;
import com.steam.xbcc.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class LoginUserDetailsService implements UserDetailsService {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.根据账号查询用户信息
        Login login = selectLoginByUserName(username);
        if (login != null) {
            // 2.根据用户id查询用户权限信息
            List<Permission> permissions = permissionService.selectByLoginId(login.getId());
            if (permissions != null) {

                List<SimpleGrantedAuthority> collect = permissions.stream().map(p -> new SimpleGrantedAuthority(p.getSn())
                ).collect(Collectors.toList());


                LoginContextDto loginContextDto = new LoginContextDto(login.getId(), login.getUsername());
                return new User(JSON.toJSONString(loginContextDto),
                        login.getPassword(),
                        login.getEnabled(),
                        login.getAccountNonExpired(),
                        login.getCredentialsNonExpired(),
                        login.getAccountNonLocked(),
                        collect);
            }

        }
        return null;
    }

    private Login selectLoginByUserName(String username) {
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);
        return loginService.selectOne(wrapper);
    }
}